// src/api/interceptors.ts
import type {
    AxiosInstance,
    InternalAxiosRequestConfig,
    AxiosResponse,
    AxiosRequestConfig
} from 'axios';

// 请求拦截器
const requestInterceptor = (
    request: InternalAxiosRequestConfig
): InternalAxiosRequestConfig | Promise<InternalAxiosRequestConfig> => {
    // 构建完整的请求 URL
    const fullUrl = new URL(request.url || '', request.baseURL).toString();
    // 如果有params就添加到url中
    const params = request.params ? new URLSearchParams(request.params as any).toString() : '';
    const completeUrl = params ? `${fullUrl}?${params}` : fullUrl;
    // 打印请求信息
    console.log('发送请求: ', {
        method: request.method?.toUpperCase() || 'GET', // 请求方法，默认值为 'GET'
        url: completeUrl,                               // 完整的请求 URL
        params: { ...request.params },                  // 查询参数，默认值为空对象
        headers: request.headers?.toJSON() || {},       // 请求头，默认值为空对象
    });

    return request;
};

const requestErrorInterceptor = (error: any) => {
    console.error('请求错误:', error);
    return Promise.reject(error);
};

// 响应拦截器
const responseInterceptor = (response: AxiosResponse) => {
    console.log('收到响应:', response); // 打印响应信息
    return response;
};

const responseErrorInterceptor = (error: any) => {
    console.error('响应错误:', error);
    return Promise.reject(error);
};

// 应用拦截器到Axios实例
export const applyInterceptors = (instance: AxiosInstance): AxiosInstance => {
    instance.interceptors.request.use(requestInterceptor, requestErrorInterceptor);
    instance.interceptors.response.use(responseInterceptor, responseErrorInterceptor);
    return instance;
};